{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8783826d-c52b-4dd7-8608-fb5c32205350",
   "metadata": {},
   "outputs": [],
   "source": [
    "import argparse\n",
    "import os\n",
    "import random\n",
    "import shutil\n",
    "import time\n",
    "import warnings\n",
    "from enum import Enum\n",
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.parallel\n",
    "import torch.backends.cudnn as cudnn\n",
    "import torch.distributed as dist\n",
    "import torch.optim\n",
    "from torch.optim.lr_scheduler import StepLR\n",
    "import torch.multiprocessing as mp\n",
    "import torch.utils.data\n",
    "import torch.utils.data.distributed\n",
    "import torchvision.transforms as transforms\n",
    "import torchvision.datasets as datasets\n",
    "import torchvision.models as models\n",
    "from torch.utils.data import Subset\n",
    "\n",
    "model_names = models.list_models(module=models)\n",
    "\n",
    "parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\n",
    "parser.add_argument('data', metavar='DIR', nargs='?', default='imagenet',\n",
    "                    help='path to dataset (default: imagenet)')\n",
    "parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18',\n",
    "                    choices=model_names,\n",
    "                    help='model architecture: ' +\n",
    "                        ' | '.join(model_names) +\n",
    "                        ' (default: resnet18)')\n",
    "parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',\n",
    "                    help='number of data loading workers (default: 4)')\n",
    "parser.add_argument('--epochs', default=90, type=int, metavar='N',\n",
    "                    help='number of total epochs to run')\n",
    "parser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n",
    "                    help='manual epoch number (useful on restarts)')\n",
    "parser.add_argument('-b', '--batch-size', default=256, type=int,\n",
    "                    metavar='N',\n",
    "                    help='mini-batch size (default: 256), this is the total '\n",
    "                         'batch size of all GPUs on the current node when '\n",
    "                         'using Data Parallel or Distributed Data Parallel')\n",
    "parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,\n",
    "                    metavar='LR', help='initial learning rate', dest='lr')\n",
    "parser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n",
    "                    help='momentum')\n",
    "parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float,\n",
    "                    metavar='W', help='weight decay (default: 1e-4)',\n",
    "                    dest='weight_decay')\n",
    "parser.add_argument('-p', '--print-freq', default=10, type=int,\n",
    "                    metavar='N', help='print frequency (default: 10)')\n",
    "parser.add_argument('--resume', default='', type=str, metavar='PATH',\n",
    "                    help='path to latest checkpoint (default: none)')\n",
    "parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',\n",
    "                    help='evaluate model on validation set')\n",
    "parser.add_argument('--pretrained', dest='pretrained', action='store_true',\n",
    "                    help='use pre-trained model')\n",
    "parser.add_argument('--world-size', default=-1, type=int,\n",
    "                    help='number of nodes for distributed training')\n",
    "parser.add_argument('--rank', default=-1, type=int,\n",
    "                    help='node rank for distributed training')\n",
    "parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,\n",
    "                    help='url used to set up distributed training')\n",
    "parser.add_argument('--dist-backend', default='nccl', type=str,\n",
    "                    help='distributed backend')\n",
    "parser.add_argument('--seed', default=None, type=int,\n",
    "                    help='seed for initializing training. ')\n",
    "parser.add_argument('--gpu', default=None, type=int,\n",
    "                    help='GPU id to use.')\n",
    "parser.add_argument('--multiprocessing-distributed', action='store_true',\n",
    "                    help='Use multi-processing distributed training to launch '\n",
    "                         'N processes per node, which has N GPUs. This is the '\n",
    "                         'fastest way to use PyTorch for either single node or '\n",
    "                         'multi node data parallel training')\n",
    "parser.add_argument('--dummy', action='store_true', help=\"use fake data to benchmark\")\n",
    "\n",
    "best_acc1 = 0\n",
    "\n",
    "\n",
    "def main():\n",
    "    args = parser.parse_args()\n",
    "\n",
    "    if args.seed is not None:\n",
    "        random.seed(args.seed)\n",
    "        torch.manual_seed(args.seed)\n",
    "        cudnn.deterministic = True\n",
    "        cudnn.benchmark = False\n",
    "        warnings.warn('You have chosen to seed training. '\n",
    "                      'This will turn on the CUDNN deterministic setting, '\n",
    "                      'which can slow down your training considerably! '\n",
    "                      'You may see unexpected behavior when restarting '\n",
    "                      'from checkpoints.')\n",
    "\n",
    "    if args.gpu is not None:\n",
    "        warnings.warn('You have chosen a specific GPU. This will completely '\n",
    "                      'disable data parallelism.')\n",
    "\n",
    "    if args.dist_url == \"env://\" and args.world_size == -1:\n",
    "        args.world_size = int(os.environ[\"WORLD_SIZE\"])\n",
    "\n",
    "    args.distributed = args.world_size > 1 or args.multiprocessing_distributed\n",
    "\n",
    "    ngpus_per_node = torch.cuda.device_count()\n",
    "    if args.multiprocessing_distributed:\n",
    "        # Since we have ngpus_per_node processes per node, the total world_size\n",
    "        # needs to be adjusted accordingly\n",
    "        args.world_size = ngpus_per_node * args.world_size\n",
    "        # Use torch.multiprocessing.spawn to launch distributed processes: the\n",
    "        # main_worker process function\n",
    "        mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))\n",
    "    else:\n",
    "        # Simply call main_worker function\n",
    "        main_worker(args.gpu, ngpus_per_node, args)\n",
    "\n",
    "\n",
    "def main_worker(gpu, ngpus_per_node, args):\n",
    "    global best_acc1\n",
    "    args.gpu = gpu\n",
    "\n",
    "    if args.gpu is not None:\n",
    "        print(\"Use GPU: {} for training\".format(args.gpu))\n",
    "\n",
    "    if args.distributed:\n",
    "        if args.dist_url == \"env://\" and args.rank == -1:\n",
    "            args.rank = int(os.environ[\"RANK\"])\n",
    "        if args.multiprocessing_distributed:\n",
    "            # For multiprocessing distributed training, rank needs to be the\n",
    "            # global rank among all the processes\n",
    "            args.rank = args.rank * ngpus_per_node + gpu\n",
    "        dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,\n",
    "                                world_size=args.world_size, rank=args.rank)\n",
    "    # create model\n",
    "    if args.pretrained:\n",
    "        print(\"=> using pre-trained model '{}'\".format(args.arch))\n",
    "        model = models.__dict__[args.arch](pretrained=True)\n",
    "    else:\n",
    "        print(\"=> creating model '{}'\".format(args.arch))\n",
    "        model = models.__dict__[args.arch]()\n",
    "\n",
    "    if not torch.cuda.is_available():\n",
    "        print('using CPU, this will be slow')\n",
    "    elif args.distributed:\n",
    "        # For multiprocessing distributed, DistributedDataParallel constructor\n",
    "        # should always set the single device scope, otherwise,\n",
    "        # DistributedDataParallel will use all available devices.\n",
    "        if args.gpu is not None:\n",
    "            torch.cuda.set_device(args.gpu)\n",
    "            model.cuda(args.gpu)\n",
    "            # When using a single GPU per process and per\n",
    "            # DistributedDataParallel, we need to divide the batch size\n",
    "            # ourselves based on the total number of GPUs of the current node.\n",
    "            args.batch_size = int(args.batch_size / ngpus_per_node)\n",
    "            args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node)\n",
    "            model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])\n",
    "        else:\n",
    "            model.cuda()\n",
    "            # DistributedDataParallel will divide and allocate batch_size to all\n",
    "            # available GPUs if device_ids are not set\n",
    "            model = torch.nn.parallel.DistributedDataParallel(model)\n",
    "    elif args.gpu is not None:\n",
    "        torch.cuda.set_device(args.gpu)\n",
    "        model = model.cuda(args.gpu)\n",
    "    else:\n",
    "        # DataParallel will divide and allocate batch_size to all available GPUs\n",
    "        if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):\n",
    "            model.features = torch.nn.DataParallel(model.features)\n",
    "            model.cuda()\n",
    "        else:\n",
    "            model = torch.nn.DataParallel(model).cuda()\n",
    "\n",
    "    # define loss function (criterion), optimizer, and learning rate scheduler\n",
    "    criterion = nn.CrossEntropyLoss().cuda(args.gpu)\n",
    "\n",
    "    optimizer = torch.optim.SGD(model.parameters(), args.lr,\n",
    "                                momentum=args.momentum,\n",
    "                                weight_decay=args.weight_decay)\n",
    "    \n",
    "    \"\"\"Sets the learning rate to the initial LR decayed by 10 every 30 epochs\"\"\"\n",
    "    scheduler = StepLR(optimizer, step_size=30, gamma=0.1)\n",
    "    \n",
    "    # optionally resume from a checkpoint\n",
    "    if args.resume:\n",
    "        if os.path.isfile(args.resume):\n",
    "            print(\"=> loading checkpoint '{}'\".format(args.resume))\n",
    "            if args.gpu is None:\n",
    "                checkpoint = torch.load(args.resume)\n",
    "            else:\n",
    "                # Map model to be loaded to specified single gpu.\n",
    "                loc = 'cuda:{}'.format(args.gpu)\n",
    "                checkpoint = torch.load(args.resume, map_location=loc)\n",
    "            args.start_epoch = checkpoint['epoch']\n",
    "            best_acc1 = checkpoint['best_acc1']\n",
    "            if args.gpu is not None:\n",
    "                # best_acc1 may be from a checkpoint from a different GPU\n",
    "                best_acc1 = best_acc1.to(args.gpu)\n",
    "            model.load_state_dict(checkpoint['state_dict'])\n",
    "            optimizer.load_state_dict(checkpoint['optimizer'])\n",
    "            scheduler.load_state_dict(checkpoint['scheduler'])\n",
    "            print(\"=> loaded checkpoint '{}' (epoch {})\"\n",
    "                  .format(args.resume, checkpoint['epoch']))\n",
    "        else:\n",
    "            print(\"=> no checkpoint found at '{}'\".format(args.resume))\n",
    "\n",
    "\n",
    "    # Data loading code\n",
    "    if args.dummy:\n",
    "        print(\"=> Dummy data is used!\")\n",
    "        train_dataset = datasets.FakeData(1000, (3, 224, 224), 1000, transforms.ToTensor())\n",
    "        val_dataset = datasets.FakeData(1000, (3, 224, 224), 1000, transforms.ToTensor())\n",
    "    else:\n",
    "        traindir = os.path.join(args.data, 'train')\n",
    "        valdir = os.path.join(args.data, 'val')\n",
    "        normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n",
    "                                     std=[0.229, 0.224, 0.225])\n",
    "\n",
    "        train_dataset = datasets.ImageFolder(\n",
    "            traindir,\n",
    "            transforms.Compose([\n",
    "                transforms.RandomResizedCrop(224),\n",
    "                transforms.RandomHorizontalFlip(),\n",
    "                transforms.ToTensor(),\n",
    "                normalize,\n",
    "            ]))\n",
    "\n",
    "        val_dataset = datasets.ImageFolder(\n",
    "            valdir,\n",
    "            transforms.Compose([\n",
    "                transforms.Resize(256),\n",
    "                transforms.CenterCrop(224),\n",
    "                transforms.ToTensor(),\n",
    "                normalize,\n",
    "            ]))\n",
    "\n",
    "    if args.distributed:\n",
    "        train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)\n",
    "        val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset, shuffle=False, drop_last=True)\n",
    "    else:\n",
    "        train_sampler = None\n",
    "        val_sampler = None\n",
    "\n",
    "    train_loader = torch.utils.data.DataLoader(\n",
    "        train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),\n",
    "        num_workers=args.workers, pin_memory=True, sampler=train_sampler)\n",
    "\n",
    "    val_loader = torch.utils.data.DataLoader(\n",
    "        val_dataset, batch_size=args.batch_size, shuffle=False,\n",
    "        num_workers=args.workers, pin_memory=True, sampler=val_sampler)\n",
    "\n",
    "    if args.evaluate:\n",
    "        validate(val_loader, model, criterion, args)\n",
    "        return\n",
    "\n",
    "    for epoch in range(args.start_epoch, args.epochs):\n",
    "        if args.distributed:\n",
    "            train_sampler.set_epoch(epoch)\n",
    "\n",
    "        # train for one epoch\n",
    "        train(train_loader, model, criterion, optimizer, epoch, args)\n",
    "\n",
    "        # evaluate on validation set\n",
    "        acc1 = validate(val_loader, model, criterion, args)\n",
    "        \n",
    "        scheduler.step()\n",
    "\n",
    "        \n",
    "        # remember best acc@1 and save checkpoint\n",
    "        is_best = acc1 > best_acc1\n",
    "        best_acc1 = max(acc1, best_acc1)\n",
    "\n",
    "        if not args.multiprocessing_distributed or (args.multiprocessing_distributed\n",
    "                and args.rank % ngpus_per_node == 0):\n",
    "            save_checkpoint({\n",
    "                'epoch': epoch + 1,\n",
    "                'arch': args.arch,\n",
    "                'state_dict': model.state_dict(),\n",
    "                'best_acc1': best_acc1,\n",
    "                'optimizer' : optimizer.state_dict(),\n",
    "                'scheduler' : scheduler.state_dict()\n",
    "            }, is_best)\n",
    "\n",
    "\n",
    "def train(train_loader, model, criterion, optimizer, epoch, args):\n",
    "    batch_time = AverageMeter('Time', ':6.3f')\n",
    "    data_time = AverageMeter('Data', ':6.3f')\n",
    "    losses = AverageMeter('Loss', ':.4e')\n",
    "    top1 = AverageMeter('Acc@1', ':6.2f')\n",
    "    top5 = AverageMeter('Acc@5', ':6.2f')\n",
    "    progress = ProgressMeter(\n",
    "        len(train_loader),\n",
    "        [batch_time, data_time, losses, top1, top5],\n",
    "        prefix=\"Epoch: [{}]\".format(epoch))\n",
    "\n",
    "    # switch to train mode\n",
    "    model.train()\n",
    "\n",
    "    end = time.time()\n",
    "    for i, (images, target) in enumerate(train_loader):\n",
    "        # measure data loading time\n",
    "        data_time.update(time.time() - end)\n",
    "\n",
    "        if args.gpu is not None:\n",
    "            images = images.cuda(args.gpu, non_blocking=True)\n",
    "        if torch.cuda.is_available():\n",
    "            target = target.cuda(args.gpu, non_blocking=True)\n",
    "\n",
    "        # compute output\n",
    "        output = model(images)\n",
    "        loss = criterion(output, target)\n",
    "\n",
    "        # measure accuracy and record loss\n",
    "        acc1, acc5 = accuracy(output, target, topk=(1, 5))\n",
    "        losses.update(loss.item(), images.size(0))\n",
    "        top1.update(acc1[0], images.size(0))\n",
    "        top5.update(acc5[0], images.size(0))\n",
    "\n",
    "        # compute gradient and do SGD step\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "        # measure elapsed time\n",
    "        batch_time.update(time.time() - end)\n",
    "        end = time.time()\n",
    "\n",
    "        if i % args.print_freq == 0:\n",
    "            progress.display(i + 1)\n",
    "\n",
    "\n",
    "def validate(val_loader, model, criterion, args):\n",
    "\n",
    "    def run_validate(loader, base_progress=0):\n",
    "        with torch.no_grad():\n",
    "            end = time.time()\n",
    "            for i, (images, target) in enumerate(loader):\n",
    "                i = base_progress + i\n",
    "                if args.gpu is not None:\n",
    "                    images = images.cuda(args.gpu, non_blocking=True)\n",
    "                if torch.cuda.is_available():\n",
    "                    target = target.cuda(args.gpu, non_blocking=True)\n",
    "\n",
    "                # compute output\n",
    "                output = model(images)\n",
    "                loss = criterion(output, target)\n",
    "\n",
    "                # measure accuracy and record loss\n",
    "                acc1, acc5 = accuracy(output, target, topk=(1, 5))\n",
    "                losses.update(loss.item(), images.size(0))\n",
    "                top1.update(acc1[0], images.size(0))\n",
    "                top5.update(acc5[0], images.size(0))\n",
    "\n",
    "                # measure elapsed time\n",
    "                batch_time.update(time.time() - end)\n",
    "                end = time.time()\n",
    "\n",
    "                if i % args.print_freq == 0:\n",
    "                    progress.display(i + 1)\n",
    "\n",
    "    batch_time = AverageMeter('Time', ':6.3f', Summary.NONE)\n",
    "    losses = AverageMeter('Loss', ':.4e', Summary.NONE)\n",
    "    top1 = AverageMeter('Acc@1', ':6.2f', Summary.AVERAGE)\n",
    "    top5 = AverageMeter('Acc@5', ':6.2f', Summary.AVERAGE)\n",
    "    progress = ProgressMeter(\n",
    "        len(val_loader) + (args.distributed and (len(val_loader.sampler) * args.world_size < len(val_loader.dataset))),\n",
    "        [batch_time, losses, top1, top5],\n",
    "        prefix='Test: ')\n",
    "\n",
    "    # switch to evaluate mode\n",
    "    model.eval()\n",
    "\n",
    "    run_validate(val_loader)\n",
    "    if args.distributed:\n",
    "        top1.all_reduce()\n",
    "        top5.all_reduce()\n",
    "\n",
    "    if args.distributed and (len(val_loader.sampler) * args.world_size < len(val_loader.dataset)):\n",
    "        aux_val_dataset = Subset(val_loader.dataset,\n",
    "                                 range(len(val_loader.sampler) * args.world_size, len(val_loader.dataset)))\n",
    "        aux_val_loader = torch.utils.data.DataLoader(\n",
    "            aux_val_dataset, batch_size=args.batch_size, shuffle=False,\n",
    "            num_workers=args.workers, pin_memory=True)\n",
    "        run_validate(aux_val_loader, len(val_loader))\n",
    "\n",
    "    progress.display_summary()\n",
    "\n",
    "    return top1.avg\n",
    "\n",
    "\n",
    "def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n",
    "    torch.save(state, filename)\n",
    "    if is_best:\n",
    "        shutil.copyfile(filename, 'model_best.pth.tar')\n",
    "\n",
    "class Summary(Enum):\n",
    "    NONE = 0\n",
    "    AVERAGE = 1\n",
    "    SUM = 2\n",
    "    COUNT = 3\n",
    "\n",
    "class AverageMeter(object):\n",
    "    \"\"\"Computes and stores the average and current value\"\"\"\n",
    "    def __init__(self, name, fmt=':f', summary_type=Summary.AVERAGE):\n",
    "        self.name = name\n",
    "        self.fmt = fmt\n",
    "        self.summary_type = summary_type\n",
    "        self.reset()\n",
    "\n",
    "    def reset(self):\n",
    "        self.val = 0\n",
    "        self.avg = 0\n",
    "        self.sum = 0\n",
    "        self.count = 0\n",
    "\n",
    "    def update(self, val, n=1):\n",
    "        self.val = val\n",
    "        self.sum += val * n\n",
    "        self.count += n\n",
    "        self.avg = self.sum / self.count\n",
    "\n",
    "    def all_reduce(self):\n",
    "        device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "        total = torch.tensor([self.sum, self.count], dtype=torch.float32, device=device)\n",
    "        dist.all_reduce(total, dist.ReduceOp.SUM, async_op=False)\n",
    "        self.sum, self.count = total.tolist()\n",
    "        self.avg = self.sum / self.count\n",
    "\n",
    "    def __str__(self):\n",
    "        fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'\n",
    "        return fmtstr.format(**self.__dict__)\n",
    "    \n",
    "    def summary(self):\n",
    "        fmtstr = ''\n",
    "        if self.summary_type is Summary.NONE:\n",
    "            fmtstr = ''\n",
    "        elif self.summary_type is Summary.AVERAGE:\n",
    "            fmtstr = '{name} {avg:.3f}'\n",
    "        elif self.summary_type is Summary.SUM:\n",
    "            fmtstr = '{name} {sum:.3f}'\n",
    "        elif self.summary_type is Summary.COUNT:\n",
    "            fmtstr = '{name} {count:.3f}'\n",
    "        else:\n",
    "            raise ValueError('invalid summary type %r' % self.summary_type)\n",
    "        \n",
    "        return fmtstr.format(**self.__dict__)\n",
    "\n",
    "\n",
    "class ProgressMeter(object):\n",
    "    def __init__(self, num_batches, meters, prefix=\"\"):\n",
    "        self.batch_fmtstr = self._get_batch_fmtstr(num_batches)\n",
    "        self.meters = meters\n",
    "        self.prefix = prefix\n",
    "\n",
    "    def display(self, batch):\n",
    "        entries = [self.prefix + self.batch_fmtstr.format(batch)]\n",
    "        entries += [str(meter) for meter in self.meters]\n",
    "        print('\\t'.join(entries))\n",
    "        \n",
    "    def display_summary(self):\n",
    "        entries = [\" *\"]\n",
    "        entries += [meter.summary() for meter in self.meters]\n",
    "        print(' '.join(entries))\n",
    "\n",
    "    def _get_batch_fmtstr(self, num_batches):\n",
    "        num_digits = len(str(num_batches // 1))\n",
    "        fmt = '{:' + str(num_digits) + 'd}'\n",
    "        return '[' + fmt + '/' + fmt.format(num_batches) + ']'\n",
    "\n",
    "def accuracy(output, target, topk=(1,)):\n",
    "    \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n",
    "    with torch.no_grad():\n",
    "        maxk = max(topk)\n",
    "        batch_size = target.size(0)\n",
    "\n",
    "        _, pred = output.topk(maxk, 1, True, True)\n",
    "        pred = pred.t()\n",
    "        correct = pred.eq(target.view(1, -1).expand_as(pred))\n",
    "\n",
    "        res = []\n",
    "        for k in topk:\n",
    "            correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)\n",
    "            res.append(correct_k.mul_(100.0 / batch_size))\n",
    "        return res\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
